<template>
  <view class="container">
    <view style="margin-top: 120rpx;"></view>
    <!-- 使用通用导航栏组件替换原有导航栏 -->
    <nav-bar :title="userId ? '编辑用户' : '新增用户'" />

    <uni-forms ref="form" :model="formData" :rules="rules">
      <!-- 非平台股东才显示用户名 -->
      <uni-forms-item label="用户名" name="name" v-if="!isPlatformShareholder">
        <uni-easyinput v-model="formData.name" placeholder="请输入用户名" />
      </uni-forms-item>
      
      <!-- 非平台股东才显示手机号 -->
      <uni-forms-item label="手机号" name="phone" v-if="!isPlatformShareholder">
        <uni-easyinput v-model="formData.phone" placeholder="请输入手机号" />
      </uni-forms-item>
      
      <!-- 非平台股东且新增用户才显示密码 -->
      <uni-forms-item label="密码" name="password" v-if="!isPlatformShareholder && !userId">
        <uni-easyinput type="password" v-model="formData.password" placeholder="请输入密码" />
      </uni-forms-item>
      
      <!-- 非平台股东且新增用户才显示确认密码 -->
      <uni-forms-item label="确认密码" name="confirm_password" v-if="!isPlatformShareholder && !userId">
        <uni-easyinput type="password" v-model="formData.confirm_password" placeholder="请再次输入密码" />
      </uni-forms-item>
      
      <!-- 非平台股东才显示角色选择 -->
      <uni-forms-item label="角色" name="roles" v-if="!isPlatformShareholder">
        <uni-data-checkbox 
          v-model="formData.roles"
          :localdata="[
            { text: '店主', value: 'owner' },
            { text: '店长', value: 'manager' },
            { text: '员工', value: 'staff' },
            { text: '客户', value: 'customer' }
          ]"
          @change="handleRoleChange"
        />
      </uni-forms-item>
      
      <!-- 平台股东信息显示区域 -->
      <view v-if="isPlatformShareholder" class="platform-shareholder-info">
        <view class="info-item">
          <text class="label">用户名：</text>
          <text class="value">{{ formData.name }}</text>
        </view>
        <view class="info-item">
          <text class="label">手机号：</text>
          <text class="value">{{ formData.phone }}</text>
        </view>
        <view class="info-item">
          <text class="label">角色：</text>
          <text class="value">平台股东</text>
        </view>
      </view>
      
      <!-- 提成比例和占股份额可以编辑，即使是平台股东 -->
      <uni-forms-item label="提成比例" name="commission_rate" v-if="formData.roles !== 'customer' || isPlatformShareholder">
        <view class="commission-input">
          <uni-easyinput 
            v-model="formData.commission_rate" 
            placeholder="请输入提成比例" 
            type="number"
          />
          <text class="percent">%</text>
        </view>
      </uni-forms-item>
      
      <uni-forms-item label="占股份额" name="equity_ratio" v-if="formData.roles !== 'customer' || isPlatformShareholder">
        <view class="commission-input">
          <uni-easyinput 
            v-model="formData.equity_ratio" 
            placeholder="请输入占股份额" 
            type="number"
          />
          <text class="percent">%</text>
        </view>
      </uni-forms-item>
      <!-- 当角色为客户时显示员工选择 -->
      <uni-forms-item v-if="formData.roles === 'customer'" label="销售员" name="staff_id" required>
        <view class="staff-container">
          <view v-for="staff in staffList" :key="staff.user_id" class="staff-item"
            :class="{ selected: formData.staff_id === staff.user_id }" @click="selectStaff(staff)">
            <text class="staff-name">{{ staff.name }}</text>
            <uni-icons :type="formData.staff_id === staff.user_id ? 'checkbox-filled' : 'checkbox'"
              :color="formData.staff_id === staff.user_id ? '#4cd964' : '#999'" size="20" />
          </view>
        </view>
      </uni-forms-item>
      <button type="primary" @click="submitForm">保存</button>
    </uni-forms>
  </view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
import userApi from '@/utils/user.js'
import store from '@/utils/store.js'

export default {
  components: {
    NavBar
  },
  data() {
    return {
      userId: '',
      storeId: '',  // 新增storeId字段
      isPlatformShareholder: false, // 是否为平台股东
      staffList: [], // 添加员工列表
      formData: {
        name: '',
        phone: '',
        password: '',
        confirm_password: '',
        roles: 'customer',  // 修改默认角色为customer
        commission_rate: '',  // 新增提成比例字段
        equity_ratio: '',  // 新增占股份额字段
        staff_id: '', // 添加销售员ID字段
      },
      rules: {
        commission_rate: {
          rules: [{
            pattern: '^\\d+(\\.\\d{1,2})?$',
            errorMessage: '请输入有效的数字，最多两位小数'
          }]
        },
        equity_ratio: {
          rules: [{
            pattern: '^\\d+(\\.\\d{1,2})?$',
            errorMessage: '请输入有效的数字，最多两位小数'
          }]
        },
        name: {
          rules: [{
            required: true,
            errorMessage: '请输入用户名',
            validateFunction: (rule, value, data, callback) => {
              // 如果是平台股东，不进行校验
              if (this.isPlatformShareholder) {
                return true;
              }
              return value && value.trim() !== '';
            }
          }]
        },
        phone: {
          rules: [{
            required: true,
            errorMessage: '请输入手机号',
            validateFunction: (rule, value, data, callback) => {
              // 如果是平台股东，不进行校验
              if (this.isPlatformShareholder) {
                return true;
              }
              return value && value.trim() !== '';
            }
          }, {
            pattern: '^1[3-9]\\d{9}$',
            errorMessage: '请输入正确的手机号码',
            validateFunction: (rule, value, data, callback) => {
              // 如果是平台股东，不进行校验
              if (this.isPlatformShareholder) {
                return true;
              }
              return !value || /^1[3-9]\d{9}$/.test(value);
            }
          }]
        },
        password: {
          rules: [{
            required: true,
            errorMessage: '请输入密码',
            validateFunction: (rule, value, data, callback) => {
              // 如果是平台股东或编辑模式，不进行校验
              if (this.isPlatformShareholder || this.userId) {
                return true;
              }
              return value && value.trim() !== '';
            }
          }, {
            minLength: 6,
            maxLength: 20,
            errorMessage: '密码长度在6-20个字符之间',
            validateFunction: (rule, value, data, callback) => {
              // 如果是平台股东或编辑模式，不进行校验
              if (this.isPlatformShareholder || this.userId) {
                return true;
              }
              return !value || (value.length >= 6 && value.length <= 20);
            }
          }]
        },
        confirm_password: {
          rules: [{
            required: true,
            errorMessage: '请再次输入密码',
            validateFunction: (rule, value, data, callback) => {
              // 如果是平台股东或编辑模式，不进行校验
              if (this.isPlatformShareholder || this.userId) {
                return true;
              }
              return value && value.trim() !== '';
            }
          }, {
            validateFunction: (rule, value, data, callback) => {
              // 如果是平台股东或编辑模式，不进行校验
              if (this.isPlatformShareholder || this.userId) {
                return true;
              }
              if (value !== this.formData.password) {
                callback('两次输入的密码不一致');
                return false;
              }
              return true;
            }
          }]
        },
        roles: {
          rules: [{
            required: true,
            errorMessage: '请选择角色',
            validateFunction: (rule, value, data, callback) => {
              // 如果是平台股东，不进行校验
              if (this.isPlatformShareholder) {
                return true;
              }
              return value && value.trim() !== '';
            }
          }]
        },
        staff_id: {
          rules: [{
            required: true,
            errorMessage: '请选择销售员',
            validateFunction: (rule, value, data, callback) => {
              if (this.formData.roles !== 'customer') {
                return true;
              }
              return value && value.trim() !== '';
            }
          }]
        },
      }
    }
  },
  onLoad(options) {
    this.userId = options.user_id
    this.storeId = options.store_id  // 接收store_id参数
    if(this.userId) {
      this.getUserDetail()
    }
      // 如果默认角色是customer，加载员工列表
    if (this.formData.roles === 'customer') {
      this.loadStaffList()
    }
  },
  methods: {
     // 添加选择员工方法
     selectStaff(staff) {
      this.formData.staff_id = staff.user_id;
    },
    
    // 加载员工列表
    async loadStaffList() {
      try {
        const staffResponse = await store.getStoreUsers(this.storeId, {
          'roles[]': ['staff', 'owner', 'manager']
        });
        this.staffList = staffResponse.list || [];
      } catch (error) {
        console.error('获取员工列表失败:', error);
        uni.showToast({
          title: '获取员工列表失败',
          icon: 'none'
        });
      }
    },
    // 修改角色变化处理方法
    handleRoleChange(e) {
      if (e === 'customer') {
        this.formData.commission_rate = '';
        this.formData.equity_ratio = '';
        // 当选择客户角色时，加载员工列表
        this.loadStaffList();
      } else if (e !== 'owner') {
        this.formData.equity_ratio = '';
      }
      // 清空之前选择的员工
      this.formData.staff_id = '';
    },
    handleAddUser() {
      uni.navigateTo({
        url: `/pages/user/edit?store_id=${this.storeId}`
      });
    },
    async getUserDetail() {
      try {
        const res = await userApi.getUserById(this.storeId,this.userId)
        console.log(res)
        
        // 检查是否为平台股东
        this.isPlatformShareholder = res.data.user_store && res.data.user_store.role === 'platform_shareholder'
        
        this.formData = {
          name: res.data.name,
          phone: res.data.phone,
          roles: res.data.user_store.role,
          commission_rate: res.data.user_store.commission_rate? (res.data.user_store.commission_rate * 100).toFixed(2) : '',
          equity_ratio: res.data.user_store.equity_ratio? (res.data.user_store.equity_ratio * 100).toFixed(2) : ''
        }
        // 如果默认角色是customer，加载员工列表
        if ( this.formData.roles === 'customer') {
          this.loadStaffList()
        }
      } catch (error) {
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      }
    },
    async submitForm() {
      try {
  
        
        // 如果是平台股东，只提交允许修改的字段
        let submitData = {}
        
        if (this.isPlatformShareholder) {
          submitData = {
            store_id: this.storeId,
            commission_rate: this.formData.commission_rate ? parseFloat(this.formData.commission_rate) / 100 : 0,
            equity_ratio: this.formData.equity_ratio ? parseFloat(this.formData.equity_ratio) / 100 : 0
          }
        } else {
          await this.$refs.form.validate()
          submitData = {
            ...this.formData,
            store_id: this.storeId,
            commission_rate: this.formData.commission_rate ? parseFloat(this.formData.commission_rate) / 100 : 0,
            equity_ratio: this.formData.equity_ratio ? parseFloat(this.formData.equity_ratio) / 100 : 0
          }
        }
        
        if (this.userId) {
          await userApi.updateUser(this.userId, submitData)
          uni.showToast({
            title: '修改成功',
            icon: 'success'
          })
        } else {
          await userApi.createUser(submitData)
          uni.showToast({
            title: '新增成功',
            icon: 'success'
          })
        }
        uni.$emit('refreshUserList')
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        // 区分前端验证错误和后端API错误
        console.error(error);
        if (error.code && error.code==400) {
          // 后端API返回的错误（如股份比例超过100%）
          uni.showModal({
            title: '操作失败',
            content: error.message || '服务器返回错误',
            showCancel: false,
            confirmText: '确定'
          });
        } else {
          // 前端验证错误或其他客户端错误
          uni.showToast({
            title: error.message || '表单验证失败',
            icon: 'none',
            duration: 2000
          });
        }
      }
    },
    navigateBack() {
      uni.navigateBack();
    },
  }
}
</script>

<style>
.container {
  padding: 0 30rpx;
  background-color: #f5f5f5;
}

/* 删除原有的nav-bar相关样式 */

uni-forms {
  margin: 0 -30rpx;
  padding: 20rpx 30rpx;
  background-color: #fff;
}
.commission-input {
  display: flex;
  align-items: center;
  width: 50%;
}
.percent {
  margin-left: 10rpx;
  color: #666;
}

/* 平台股东信息显示样式 */
.platform-shareholder-info {
  background-color: #f8f8f8;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}
.info-item {
  display: flex;
  padding: 10rpx 0;
}
.info-item .label {
  width: 150rpx;
  color: #666;
}
.info-item .value {
  flex: 1;
  color: #333;
  font-weight: 500;
}
/* 添加员工选择样式 */
.staff-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15rpx;
  padding: 10rpx;
}

.staff-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  background-color: #fff;
}

.staff-item.selected {
  background-color: #4cd964;
  border-color: #4cd964;
  color: white;
}

.staff-name {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.staff-item.selected .staff-name {
  color: white;
}
</style>